﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Common
{
    /// <summary>
    /// 操作json文件
    /// </summary>
    public static class JsonFileHelp
    {
        /// <summary>
        /// 读取json文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="key">key</param>
        /// <returns></returns>
        public static string ReadJsonFile(string path,string key)
        {
            string jsonfile = path;//JSON文件路径

            using (System.IO.StreamReader file = System.IO.File.OpenText(path))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    JObject o = (JObject)JToken.ReadFrom(reader);
                    var value = o[key].ToString();
                    return value;
                }
            }
        }

        /// <summary>
        /// 修改json文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="json">修改的json字符串</param>
        /// <param name="key">修改的节点key</param>
        public static bool UpdateJsonFile(string path,string json, string key)
        {
            try
            {
                JObject jObj;
                using (StreamReader file = new StreamReader(path))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    jObj = (JObject)JToken.ReadFrom(reader);
                    if (string.IsNullOrEmpty(json))
                        jObj[key] = "";
                    else jObj[key] = JObject.Parse(json);
                }
                using (var writer = new StreamWriter(path))
                using (var jsonWriter = new JsonTextWriter(writer))
                {
                    jObj.WriteTo(jsonWriter);
                    return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
